<template>
  <div class="source" v-if="isLogin">
    <pageHeader :active="6" :bgColor="'#292c4d'"></pageHeader>
    <div class="page-content">
      <div class="mt70 add-source">
        <div
          class="source-img pr"
          @mouseenter="show = true"
          @mouseleave="show = false"
        >
          <img src="../../assets/images/addService.png" alt="" width="100%" />
          <div class="describe">入驻申请</div>
          <div class="modal" v-show="show">
            <div class="join-btn">
              <p class="cfff f16 mb10">提交使用反馈，获取专属服务</p>
              <el-button type="primary" size="small">立即反馈</el-button>
            </div>
          </div>
        </div>
      </div>
      <div class="content">
        <div class="naver">
          <el-button size="small" @click="add(1)">新增场景</el-button>
          <!-- <el-button size="small" @click="add(2)">新增产品</el-button> -->
        </div>
        <el-table
          ref="dataTable"
          :data="sceneList"
          highlight-current-row
          border
          row-key="id"
          id="sence-tbody"
          style="width: 100%"
          :header-cell-style="{
            background: '#f0f0f0',
            color: '#333',
            height: '28px'
          }"
          :row-style="{ height: '28px' }"
          :cell-style="{ padding: '4px' }"
        >
          <el-table-column
            align="center"
            type="index"
            width="50"
          ></el-table-column>
          <el-table-column
            header-align="center"
            align="left"
            label="场景名称"
            prop="name"
          ></el-table-column>
          <el-table-column
            align="center"
            label="创建时间"
            width="190"
            prop="createTime"
          ></el-table-column>
          <el-table-column
            align="center"
            label="更新时间"
            width="190"
            prop="updateTime"
          ></el-table-column>
          <el-table-column width="160" align="center" label="操作">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="detailPord(scope.row)"
                >查看产品</el-button
              >
              <el-button
                size="mini"
                type="text"
                @click="handleEdit(1, scope.row)"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="text"
                @click="handleDelete(1, scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <pageFooter></pageFooter>
    <el-dialog
      :title="type == 1 ? '新增场景' : '新增产品'"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      class="dialog-box"
    >
      <el-form
        ref="ruleForm"
        :model="form"
        :rules="rules"
        label-position="left"
        label-width="80px"
      >
        <el-form-item :label="type == 1 ? '场景名称' : '产品名称'" prop="name">
          <el-input v-model="form.name" clearable autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- ///////// 查好看产品 ///////// -->
    <el-dialog
      title="产品信息"
      :visible.sync="dialogPordVisible"
      :close-on-click-modal="false"
      :before-close="handleClose"
      width="80%"
    >
      <div style="margin-bottom: 8px; display: flex; justify-content: end">
        <el-button size="small" @click="add(2)">新增产品</el-button>
      </div>
      <el-table
        ref="pordTable"
        :data="produceList"
        highlight-current-row
        border
        row-key="id"
        id="pord-tbody"
        style="width: 100%"
        :header-cell-style="{
          background: '#f0f0f0',
          color: '#333',
          height: '28px'
        }"
        :row-style="{ height: '28px' }"
        :cell-style="{ padding: '2px' }"
      >
        <el-table-column
          align="center"
          type="index"
          width="50"
        ></el-table-column>
        <el-table-column
          header-align="center"
          align="left"
          label="产品名称"
          prop="name"
        ></el-table-column>
        <el-table-column
          align="center"
          label="创建时间"
          width="170"
          prop="createTime"
        ></el-table-column>
        <el-table-column
          align="center"
          label="更新时间"
          width="170"
          prop="updateTime"
        ></el-table-column>
        <el-table-column align="center" width="280" label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="showChild(scope.row, 822746444562432, (showTable = 1))"
              >功能模块</el-button
            >
            <!-- <el-button
              size="mini"
              type="text"
              @click="showChild(scope.row, 822754483765248, (showTable = 2))"
              >数据目录</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="showChild(scope.row, 822756023697408, (showTable = 3))"
              >数据服务</el-button
            > -->
            <el-button size="mini" type="text" @click="handleEdit(2, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleDelete(2, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- ///////// 编辑场景/产品 //////// -->
    <el-dialog
      :title="type == 1 ? '编辑场景' : '编辑产品'"
      :visible.sync="dialogEdit"
      :close-on-click-modal="false"
      class="dialog-box"
    >
      <el-form
        ref="editForm"
        :model="formEdit"
        :rules="rules"
        label-position="left"
        label-width="80px"
      >
        <el-form-item :label="type == 1 ? '编辑场景' : '编辑产品'" prop="name">
          <el-input
            v-model="formEdit.name"
            clearable
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEdit = false">取 消</el-button>
        <el-button type="primary" @click="updateForm('editForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- /////// 新增第三级数据 //////// -->
    <el-dialog
      :title="
        showTable === 1
          ? '新增功能模块'
          : showTable === 2
          ? '新增数据目录主题'
          : '新增数据服务主题'
      "
      :visible.sync="addOrEditChild"
      :close-on-click-modal="false"
      class="dialog-box"
    >
      <el-form
        ref="childForm"
        :model="childForm"
        :rules="rules"
        label-position="left"
        label-width="140px"
      >
        <el-form-item
          :label="
            showTable === 1
              ? '功能模块名称'
              : showTable === 2
              ? '数据目录主题名称'
              : '数据服务主题名称'
          "
          prop="name"
        >
          <el-input
            v-model="childForm.name"
            clearable
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addOrEditChild = false">取 消</el-button>
        <el-button type="primary" @click="saveChildForm()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- /////// 编辑第三级数据 //////// -->
    <el-dialog
      :title="
        showTable === 1
          ? '编辑功能模块'
          : showTable === 2
          ? '编辑数据目录主题'
          : '编辑数据服务主题'
      "
      :visible.sync="EditChild"
      :close-on-click-modal="false"
      :before-close="handleCloseChild"
      class="dialog-box"
    >
      <el-form
        ref="childForm"
        :model="childForm"
        :rules="rules"
        label-position="left"
        label-width="140px"
      >
        <el-form-item
          :label="
            showTable === 1
              ? '功能模块名称'
              : showTable === 2
              ? '数据目录主题名称'
              : '数据服务主题名称'
          "
          prop="name"
        >
          <el-input
            v-model="childForm.name"
            clearable
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="EditChild = false">取 消</el-button>
        <el-button type="primary" @click="updateChildForm()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- ///////// 查看第三级数据 ///////// -->
    <el-dialog
      :title="
        showTable === 1
          ? '功能模块信息'
          : showTable === 2
          ? '数据目录主题信息'
          : '数据服务主题信息'
      "
      :visible.sync="showTableThird"
      :close-on-click-modal="false"
      width="80%"
    >
      <div style="margin-bottom: 8px; display: flex; justify-content: end">
        <el-button size="small" @click="addLastChild(showTable)">{{
          showTable === 1
            ? '新增功能模块'
            : showTable === 2
            ? '新增数据目录主题'
            : '新增数据服务主题'
        }}</el-button>
      </div>
      <el-table
        ref="childTable"
        :data="moduleList"
        highlight-current-row
        border
        row-key="id"
        id="child-tbody"
        style="width: 100%"
        :header-cell-style="{
          background: '#f0f0f0',
          color: '#333',
          height: '28px'
        }"
        :row-style="{ height: '28px' }"
        :cell-style="{ padding: '2px' }"
      >
        <el-table-column
          align="center"
          type="index"
          width="50"
        ></el-table-column>
        <el-table-column
          header-align="center"
          align="left"
          :label="
            showTable === 1
              ? '功能模块名称'
              : showTable === 2
              ? '数据目录主题名称'
              : '数据服务主题名称'
          "
          prop="name"
        ></el-table-column>
        <el-table-column
          align="center"
          label="创建时间"
          width="170"
          prop="createTime"
        ></el-table-column>
        <el-table-column
          align="center"
          label="更新时间"
          width="170"
          prop="updateTime"
        ></el-table-column>
        <el-table-column align="center" width="280" label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleEditChild(showTable, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleDeleteChild(showTable, scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import pageHeader from '@/components/pageHeader.vue'
import pageFooter from '@/components/pageFooter.vue'
import {
  scene,
  product,
  saveSceneProd,
  updateSceneProd,
  delSceneProd,
  getDataSubject,
  saveDataSubject,
  delDataSubject,
  updateDataSubject,
  sortSceneProd,
  sortDataSubject
} from '@/api/sceneProduct' //api接口
import { mapGetters } from 'vuex'
import Sortable from 'sortablejs'

export default {
  name: 'SettingPro',
  computed: {
    // 获取状态管路设置的值
    ...mapGetters(['isLogin'])
  },
  data() {
    return {
      dialogFormVisible: false,
      dialogPordVisible: false,
      showTableThird: false,
      dialogEdit: false,
      addOrEditChild: false,
      EditChild: false,
      showTable: '',
      tableType: 1,
      productId: 0,
      parentId: 0,
      show: false,
      type: 1,
      form: {},
      formEdit: {},
      childForm: {},
      sceneList: [],
      produceList: [],
      moduleList: [],
      rules: {
        name: [
          {
            required: true,
            message: '请输入标题名称',
            trigger: 'blur'
          }
        ]
        // parentId: [
        //   {
        //     required: true,
        //     message: '请选择',
        //     trigger: 'blur'
        //   }
        // ]
      }
    }
  },
  components: { pageHeader, pageFooter },

  created() {
    this.initData()
  },
  mounted() {
    // setTimeout(() => {
    // this.rowDrop()
    // },4000)
  },
  methods: {
    rowDrop() {
      // const tbody = document.querySelector(
      //   '.draggable .el-table__body-wrapper tbody'
      // )
      // const tbody = this.$refs.dataTable.$el.querySelectorAll(
      //   '.el-table__body-wrapper > table > tbody'
      // )[0]
      // const tbody = document.querySelector('#sence-tbody .el-table__body-wrapper tbody')
      let tbody = undefined
      if (this.tableType === 1) {
        tbody = document.querySelector(
          '#sence-tbody .el-table__body-wrapper tbody'
        )
      } else if (this.tableType === 2) {
        tbody = document.querySelector(
          '#pord-tbody .el-table__body-wrapper tbody'
        )
      } else if(this.tableType === 3){
        tbody = document.querySelector(
          '#child-tbody .el-table__body-wrapper tbody'
        )
      }
      const that = this
      // console.log('87878787', tbody)
      Sortable.create(tbody, {
        //  指定父元素下可被拖拽的子元素
        // draggable: '.draggable .el-table__row',
        onEnd({ newIndex, oldIndex }) {
          if (that.tableType === 1) {
            const currRow = that.sceneList.splice(oldIndex, 1)[0]
            that.sceneList.splice(newIndex, 0, currRow)
            // console.log('场景', that.sceneList)
            let arr = []
            that.sceneList.forEach((item, i) => {
              arr.push({
                id: item.id,
                parentId: 0,
                orderNum: i
              })
            })
            that.sort(1,arr)
          } else if (that.tableType === 2) {
            const currRow = that.produceList.splice(oldIndex, 1)[0]
            that.produceList.splice(newIndex, 0, currRow)
            // console.log('产品', that.produceList)
            let arr = []
            that.produceList.forEach((item, i) => {
              arr.push({
                id: item.id,
                parentId: item.parentId,
                orderNum: i
              })
            })
            that.sort(1,arr)
          } else if(that.tableType === 3) {
            const currRow = that.moduleList.splice(oldIndex, 1)[0]
            that.moduleList.splice(newIndex, 0, currRow)
            // console.log('模块', that.moduleList)
            let arr = []
            that.moduleList.forEach((item, i) => {
              arr.push({
                id: item.id,
                menuId: 822746444562432,
                productId: item.productId,
                orderNum: i
              })
            })
            that.sort(2,arr)
          }
        }
      })
    },
    sort(type, data){
      if(type === 1){
        sortSceneProd(data).then(res => {
          if(res.code === 0){
            this.$message({
              message: res.msg,
              type: 'success'
            })
          }
        })
      } else {
        sortDataSubject(data).then(res => {
          if(res.code === 0){
            this.$message({
              message: res.msg,
              type: 'success'
            })
          }
        })
      }
    },
    handleClose(done) {
      this.tableType = 1
      done()
    },
    handleCloseChild(done){
      this.tableType = 2
      done()
    },
    async detailPord(row) {
      this.tableType = 2
      this.dialogPordVisible = true
      this.parentId = row.id
      await this.getProduceList(row.id)
    },
    addLastChild(lastChildType) {
      this.childForm = {}
      this.addOrEditChild = true
    },
    saveChildForm() {
      this.childForm.productId = this.productId
      if (this.showTable === 1) {
        this.childForm.menuId = 822746444562432
        // console.log('功能模块', this.childForm)
      } else if (this.showTable === 2) {
        this.childForm.menuId = 822754483765248
        // console.log('数据目录', this.childForm)
      } else if (this.showTable === 3) {
        this.childForm.menuId = 822756023697408
        // console.log('数据服务', this.childForm)
      }
      saveDataSubject(this.childForm).then((res) => {
        if (res.code === 0) {
          this.$message({
            message: res.msg,
            type: 'success'
          })
          this.addOrEditChild = false
          this.getDataSubjectList(this.productId, this.childForm.menuId)
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    updateChildForm() {
      // console.log('更新', this.childForm)
      const data = {
        menuId: this.childForm.menuId,
        name: this.childForm.name,
        productId: this.childForm.productId
      }
      updateDataSubject(data, this.childForm.id).then((res) => {
        if (res.code === 0) {
          this.$message({
            message: res.msg,
            type: 'success'
          })
          this.EditChild = false
          this.getDataSubjectList(
            this.childForm.productId,
            this.childForm.menuId
          )
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    handleEditChild(type, row) {
      this.EditChild = true
      this.childForm = row
    },
    handleDeleteChild(type, id) {
      let menuId =
        type === 1
          ? 822746444562432
          : type === 2
          ? 822754483765248
          : 822756023697408
      delDataSubject(id).then((res) => {
        if (res.code === 0) {
          this.$message({
            message: res.msg,
            type: 'success'
          })
          this.getDataSubjectList(this.productId, menuId)
        }
      })
    },
    getDataSubjectList(productId, menuId) {
      getDataSubject(productId, menuId).then((res) => {
        this.moduleList = res.data || []
        this.$nextTick(() => {
          this.rowDrop()
        })
      })
    },
    showChild(row, menuId) {
      this.tableType = 3
      this.getDataSubjectList(row.id, menuId)
      this.showTableThird = true
      this.productId = row.id
    },
    handleDelete(type, row) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delSceneProd(row.id).then((res) => {
            if (res.code === 0) {
              this.$message({
                type: 'success',
                message: res.msg
              })
              if (type === 1) {
                this.getScene()
              } else if (type === 2) {
                this.getProduceList(row.parentId)
              }
            }
          })
        })
        .catch(() => {})
    },
    handleEdit(type, row) {
      this.dialogEdit = true
      this.type = type
      this.formEdit = row
    },
    updateForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          updateSceneProd(this.formEdit.id, this.formEdit).then((res) => {
            if (res.code === 0) {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.dialogEdit = false
              if (this.type === 1) {
                this.getScene()
              } else if (this.type === 2) {
                this.getProduceList(this.formEdit.parentId)
              }
            } else {
              this.$message.error(res.msg)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (this.type === 1) {
            this.form.parentId = 0
            this.form.type = this.type
            await this.saveForm()
          } else if (this.type === 2) {
            this.form.type = this.type
            await this.saveForm()
          }
          // console.log(this.form)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    saveForm() {
      if (this.type === 1) {
        // 保存场景
        this.save(this.form)
      } else if (this.type === 2) {
        // 保存产品
        this.form.parentId = this.parentId
        this.form.type = this.type
        this.save(this.form)
      }
    },
    save(form) {
      saveSceneProd(form).then((res) => {
        if (res.code === 0) {
          this.$message({
            message: res.msg,
            type: 'success'
          })
          this.dialogFormVisible = false
          if (this.type === 1) {
            this.getScene()
          } else if (this.type === 2) {
            this.getProduceList(this.parentId)
            this.parentId = 0
          }
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    add(type) {
      this.form = {}
      this.dialogFormVisible = true
      this.type = type
    },
    getProduceList(parentId) {
      product(parentId).then((res) => {
        this.produceList = res.data || []
        this.$nextTick(() => {
          this.rowDrop()
        })
      })
    },
    getScene() {
      scene().then((res) => {
        // console.log('场景',res.data)
        this.sceneList = res.data || []
        this.$nextTick(() => {
          this.rowDrop()
        })
      })
    },
    initData() {
      this.getScene()
    }
  }
}
</script>

<style lang="scss" scoped>
.source {
  margin-top: 70px;
  .page-content {
    min-height: calc(100vh - 300px);
  }
  .add-source {
    background: url('../../assets/images/recourse.png') no-repeat;
    padding-top: 50px;
    background-size: 100% 300px;
    height: 200px;
    overflow: hidden;
    min-width: 1200px;
    .source-img {
      width: 50%;
      margin: 0 auto;
      padding: 15px;
      background: #fff;
      height: 100%;
      .describe {
        position: absolute;
        top: 150px;
        right: 40px;
        font-size: 18px;
        color: #fff;
      }
      .modal {
        position: absolute;
        top: 15px;
        left: 15px;
        bottom: 15px;
        right: 15px;
        background: rgba(51, 51, 51, 0.7);
      }
      .join-btn {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
    }
  }

  .add-box {
    width: 1200px;
    margin: 0 auto;
    height: 50px;
    line-height: 50px;
    text-align: right;
  }

  .content {
    display: flex;
    width: 1000px;
    margin: 0 auto;
    margin-bottom: 50px;
    flex-direction: column;
    .header {
      margin: 10px 0 -10px 229px;
      display: flex;
      justify-content: start;
    }
    .naver {
      display: flex;
      justify-content: end;
      margin: 10px 0 10px 0;
    }
    .main {
      display: flex;
      width: 1200px;
      margin: 0 auto;
      margin-bottom: 50px;
      .aside {
        width: 200px;
        margin-right: 30px;
        .nav {
          background: #efeff4;
          text-align: left;
          margin-bottom: 20px;
          &:last-child {
            margin-bottom: 0;
          }
          .title {
            height: 45px;
            display: flex;
            align-items: center;
            padding-left: 20px;
            background: #292c4d;
            color: #fff;
            font-size: 16px;
          }
          .nav-list {
            .nav-item {
              padding: 0 20px;
              height: 45px;
              display: flex;
              justify-content: space-between;
              align-items: center;
              border-left: 4px solid #efeff4;
              transition: all 0.3s;
              cursor: pointer;
              .count {
                padding: 0 10px;
                background: #fff;
                border-radius: 20px;
                color: #57aeeb;
                font-size: 12px;
              }
              &:hover {
                border-left-color: #292c4d;
                color: #292c4d;
                font-weight: bold;
              }
              &:hover .count {
                background: #efeff4;
                color: #292c4d !important;
                font-weight: bold;
              }
            }
            .active {
              background: #d6e1f2;
              border-left-color: #292c4d !important;
              color: #292c4d !important;
              font-weight: bold !important;
              .count {
                background: #efeff4 !important;
                color: #292c4d !important;
                font-weight: bold !important;
              }
            }
          }
        }
      }
      .list {
        background: rgb(242, 247, 251);
        padding: 15px 0;
        flex: 1;
        .item {
          text-align: left;
          padding: 0 20px;
          .title {
            font-size: 18px;
            margin-bottom: 10px;

            .anniu {
              float: right;
              font-size: 12px;
              color: #0a6cff;

              span {
                cursor: pointer;
              }
            }
          }
          .remark {
            font-size: 12px;
            margin-bottom: 15px;
          }
          .bb1 {
            border-bottom: 1px dotted #d6e1f2;
          }
          &:hover {
            color: #0a6cff !important;
            border: 1px solid #0a6cff;
            background: #fff;
          }
        }
      }
    }
  }

  .dialog-box {
    // text-align: left;
    .el-select {
      width: 100%;
    }
  }
}
</style>
